<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>原生WebSocket示例页面</title>
</head>
<body>
<input type="text" id="messageInput" placeholder="请输入要发送的消息">
<button onclick="sendMessage()">发送</button>
<div id="messages"></div>

<script>
    var socket = new WebSocket('ws://' + window.location.host + '/ws');

    // 建立链接事件
    socket.onopen = function(event) {
        console.log('WebSocket 连接已建立');
    };
    // 接收到消息事件
    socket.onmessage = function(event) {
        var messagesDiv = document.getElementById('messages');
        var p = document.createElement('p');
        p.textContent = event.data;
        messagesDiv.appendChild(p);
    };

    // 链接关闭事件
    socket.onclose = function(event) {
        console.log('WebSocket 连接已关闭');
    };

    // 发送消息
    function sendMessage() {
        var message = document.getElementById('messageInput').value;
        if (socket.readyState === WebSocket.OPEN) {
            socket.send(message);
        }
    }
</script>
</body>
</html>